//路由鉴权：项目当中的路由能不能被访问的设置
import router from '@/router'
import { useNProgress } from '@/hooks/web/useNProgress'
//获取用户相关的小仓库内部的token数据去判断用户是否登录成功
import { useUserStoreWithOut } from './store/modules/user'
import { useAppStoreWithOut } from './store/modules/app'

const { start, done } = useNProgress()
const useStore = useUserStoreWithOut()
const appStore = useAppStoreWithOut()

//全局前置守卫
router.beforeEach(async (to, _from, next) => {
  //进度条开始
  start()
  //获取token判断用户是否登录
  const token = useStore.token
  const username = useStore.username
  if (token) {
    //登录成功，访问login，不能访问，指向首页
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      //登录成功访问其余路由
      if (username != '请登录') {
        next()
      } else {
        try {
          //获取用户信息后再放行
          await useStore.userInfo()
          next({ ...to })
        } catch (error) {
          //token过期，获取不到用户信息或者用户手动修改本地存储token
          await useStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //用户未登录
    if (to.path == '/login') {
      next()
    } else {
      // next({ path: '/login', query: { redirect: to.path } }) // 原逻辑
      next()
    }
  }
})

//全局后置守卫
router.afterEach((to) => {
  //进度条结束
  done()
  //修改任务栏标题
  document.title = `${appStore.getTitle} - ${to.meta.title}` || 'loading'
})
